﻿

using Dapper; 
using HBase;
using hCommand;
using Net.http;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Persistence.abs {
    public abstract class AbsSysAuthorityServer :AbsWMSBaseServer, ISysAuthorityServer {

        public List<SysFile> getFile(long pid) {
            return this.opConn().Query<SysFile>("select  * from sys_file where pid=@pid and status=1" ,new { pid }).ToList();
        }
        public Page<SysFile> queryFilePage(FileDto dto) {
            string sql = "select * from sys_file where 1=1 ";
            if( !string.IsNullOrEmpty(dto.tableName) ) {
                sql += $" AND table_Name =@tableName ";
            }
            if( dto.cx > 0 && dto.sblx > 0 ) {
                sql += $" AND type = 'equp" + dto.sblx + dto.cx + "' ";
            } else if( dto.sblx > 0 ) {
                sql += $" AND type like 'equp" + dto.sblx + "_' ";
            } else if( dto.cx > 0 ) {
                sql += $" AND type like 'equp_" + dto.cx + "' ";
            }
            return this.queryPage<SysFile>(sql ,"id" ,dto);
        }

        public List<SysFile> queryFileList(FileDto dto) {
            string sql = "select * from sys_file where 1=1 ";
            if( !string.IsNullOrEmpty(dto.tableName) ) {
                sql += $" AND table_Name =@tableName ";
            }
            sql += $" AND ( type = 'equp" + dto.sblx + dto.cx + "' or type = 'equp" + dto.sblx + "') ";
            return this.opConn().Query<SysFile>(sql ,dto).ToList();
        }

        public void clearFile(long pid) {
            this.opConn().Execute("update sys_file set status=0 where pid=@pid" ,new { pid });
        }
        #region 角色
        public Page<SysRole> QueryRolePage<SysRole>(RoleDto dto) {
            string sql = "select * from sys_Role where 1=1 ";
            if( !string.IsNullOrEmpty(dto.name) ) {
                sql += $" AND name like '%{dto.name}%' ";
            }
            return this.queryPage<SysRole>(sql ,"id" ,dto);
        }
        public long AddRole(SysRole model) {
       
           
            return opConn().Insert<SysRole>(model);
        }
        public bool UpdateRole(SysRole model) {
         
            return opConn().Update<SysRole>(model);
        }
        public int DeleteRole(List<SysRole> modelList) {
            foreach( var model in modelList ) {
                readConn().Delete<SysRole>("id=" + model.id.ToString());
            }
            return 1;
        }

        public SysRole FindRoleById(long id) {
            return readConn().Get<SysRole>(id);
        }

        public List<SysRole> FindRoleByName(string name) {
            return readConn().Query<SysRole>("select * from sys_role where name=@name" ,new { name = name }).ToList();
        }
        public List<SysRole> FindAllRole() {
            return readConn().Query<SysRole>("select * from sys_role").ToList();
        }

        public List<SysMenu> FindRoleMenus(long roleId) {
            //限制了管理员的权限不允许修改，开发中先注释
            //SysRole sysRole = FindRoleById(roleId);
            //if (sysRole != null && sysRole.name.Equals("admin"))
            //{
            //    // 如果是超级管理员，返回全部
            //    return FindAllMenu();
            //}
            return readConn().Query<SysMenu>(@"select m.* from sys_menu m, sys_role_menu rm
                                                where rm.role_id = @role_id
                                                and m.id = rm.menu_id" ,new { role_id = roleId }).ToList();
        }
        public List<SysRole> FindUserRole(long userId) {
            return readConn().Query<SysRole>(@"SELECT ur.role_id id FROM  sys_user_role ur 
                                                WHERE   ur.user_ids = @user_ids" ,new { user_ids = userId }).ToList();
        }

        public int SaveRoleMenus(List<SysRoleMenu> modelList) {
            if( modelList == null || modelList.Count == 0 ) {
                return 1;
            }
            long roleId = modelList[0].roleId;
            DeleteByRoleId(roleId);
     
            String loginName = CookieHelper.LoginName(); 
            return opConn().BatchInsert(modelList);
        }

        public bool DeleteByRoleId(long roleId) {
            return opConn().Delete<SysRoleMenu>("role_id=" + roleId);
        }
        #endregion

        #region 菜单
        public List<SysMenu> FindAllMenu() {
            return readConn().Query<SysMenu>("select * from sys_menu").ToList();

        }

        public long AddMenu(SysMenu model) {
        
         
            return opConn().InsertNoNull<SysMenu>(model);
        }
        public bool UpdateMenu(SysMenu model) {
        
            return opConn().Update<SysMenu>(model);
        }

        public int DeleteMenu(List<SysMenu> modelList) {
            foreach( var model in modelList ) {
                opConn().Delete<SysMenu>("id=" + model.id.ToString());
            }
            return 1;
        }

        public List<SysMenu> FindTree(string userName ,int menuType) {
            List<SysMenu> sysMenus = new List<SysMenu>();
            List<SysMenu> menus = FindByUser(userName);
            foreach( var menu in menus ) {
                if( menu.parentId == 0 ) {
                    menu.level = 0;
                    if( !Exists(sysMenus ,menu) ) {
                        sysMenus.Add(menu);
                    }
                }
            }
            sysMenus.Sort((a ,b) => a.orderNum.CompareTo(b.orderNum));
            FindChildren(sysMenus ,menus ,menuType);
            return sysMenus;
        }

        private void FindChildren(List<SysMenu> SysMenus ,List<SysMenu> menus ,int menuType) {
            foreach( var sysMenu in SysMenus ) {
                List<SysMenu> children = new List<SysMenu>();
                foreach( var menu in menus ) {
                    if( menuType == 1 && menu.dtype == 2 ) {
                        // 如果是获取类型不需要按钮，且菜单类型是按钮的，直接过滤掉
                        continue;
                    }
                    if( sysMenu.id.Equals(menu.parentId) ) {
                        menu.parentName = sysMenu.name;
                        menu.level = sysMenu.level + 1;
                        if( !Exists(children ,menu) ) {
                            children.Add(menu);
                        }
                    }
                }
                sysMenu.children = children;
                children.Sort((a ,b) => a.orderNum.CompareTo(b.orderNum));
                FindChildren(children ,menus ,menuType);
            }
        }
        public List<SysMenu> FindByUser(String userName) {
            if( string.IsNullOrEmpty(userName) ) {
                return FindAll();
            }
            return FindByUserName(userName);
        }
        /// <summary>
        /// 根据用户名查询菜单
        /// </summary>
        /// <returns></returns>
        public List<SysMenu> FindByUserName(string userName) {
            String sql = @"select m.* from sys_menu m, sys_user u, sys_user_role ur, sys_role_menu rm
	                       where u.name = @name and u.id = ur.user_ids
  	                       and ur.role_id = rm.role_id and rm.menu_id = m.id";
            return readConn().Query<SysMenu>(sql ,new { name = userName }).ToList();
        }
        /// <summary>
        /// 查询所有菜单信息
        /// </summary>
        public List<SysMenu> FindAll() {
            string sql = @"select * from sys_menu ";
            return readConn().Query<SysMenu>(sql).ToList();
        }

        private bool Exists(List<SysMenu> sysMenus ,SysMenu sysMenu) {
            bool exist = false;
            foreach( var menu in sysMenus ) {
                if( menu.id.Equals(sysMenu.id) ) {
                    exist = true;
                }
            }
            return exist;
        }
        #endregion

        #region 用户
        public List<SysUser> GetUser(string name) {
            String sql = "select * from sys_user where name=@name";
            return readConn().Query<SysUser>(sql ,new { name = name }).ToList();
        }

        public List<SysUser> GetUser(string name ,string password) {
            String sql = "select * from sys_user where name=@name and passwords=@password";
            return readConn().Query<SysUser>(sql ,new { name = name ,password = password }).ToList();
        }

        public Page<T> QueryUserPage<T>(UserDto dto) {
            string sql = @"select u.*  from sys_user u  where 1=1";
            if( !string.IsNullOrEmpty(dto.name) ) {
                sql += $" AND u.name like '%{dto.name}%' ";
            }
            return this.queryPage<T>(sql ,"id" ,dto);
        }

        public int getByCode(SysUser model) {
            string sql = @"select count(*)  from sys_user u  where code=@code  and id<>@id";
            return readConn().QueryUnique<int>(sql ,model);
        }

        public long AddUser(SysUser model) {
  
           
            model.passwords = HUtil.MD5Encrypt("123456");
            model.auditPassword = HUtil.MD5Encrypt("123456");
            return opConn().Insert<SysUser>(model);
        }
        public bool UpdateUser(SysUser model) {
      
            model.passwords = null;
            model.auditPassword = null;
            opConn().updateNotNull(model);
            DeleteByUserId(model.id);
            foreach( var item in model.userRoles ) {
              
                item.userIds = model.id;
                opConn().Insert<SysUserRole>(item);
            }
            return true;
        }
        public bool DeleteByUserId(long userId) {
            return opConn().Delete<SysUserRole>("user_ids=" + userId);
        }

        public int DeleteUser(List<SysUser> userList) {
            foreach( var user in userList ) {
                readConn().Delete<SysUser>("id=" + user.id.ToString());
            }
            return 1;
        }

        public SysUser FindUserById(long id) {
            return readConn().Get<SysUser>(id);
        }
        public string UpdateUserPassWord(string passWord ,string oldWorld) {
            string useName = CookieHelper.LoginName();
            string passwords = HUtil.MD5Encrypt(passWord);
            string sql1 = "select * from sys_user where name=@useName";
            SysUser sysUser = opConn().QueryUnique<SysUser>(sql1 ,new { useName = useName });
            oldWorld = HUtil.MD5Encrypt(oldWorld);
            if( oldWorld != sysUser.passwords ) {
                return "与原始密码不一致";
            }
            string sql = "update sys_user set passwords=@passwords where name=@useName";
            opConn().Execute(sql ,new { passwords = passwords ,useName = useName });
            return "与原始密码一致";
        }
        public string UpdateCheckPassWord(string passWord ,string oldWorld) {
            string useName = CookieHelper.LoginName();
            string passwords = HUtil.MD5Encrypt(passWord);
            string sql1 = "select * from sys_user where name=@useName";
            SysUser sysUser = opConn().QueryUnique<SysUser>(sql1 ,new { useName = useName });
            oldWorld = HUtil.MD5Encrypt(oldWorld);
            if( oldWorld != sysUser.auditPassword ) {
                return "与原始密码不一致";
            }
            string sql = "update sys_user set audit_Password=@passwords where name=@useName";
            opConn().Execute(sql ,new { passwords = passwords ,useName = useName });
            return "与原始密码一致";
        }

    
        #endregion


       
        #region 字典
        //字典
        public Page<SysDictQuery> QueryDictsPage(DictsDto dto) {
            string sql = @"select A.*,B.dict_class_name from sys_dict A LEFT OUTER JOIN sys_dict_class B ON A.dict_class_id = B.id where 1=1";
            if( !string.IsNullOrEmpty(dto.label) ) {
                dto.label = "%" + dto.label + "%";
                sql += " AND label like @label ";
            }
            if( !string.IsNullOrEmpty(dto.dictClassId) ) {
                sql += " AND dict_Class_Id = @dictClassId ";
            }
            return this.queryPage<SysDictQuery>(sql ,"id" ,dto);
        }

        public long AddDicts(SysDict model) {

          

            return opConn().Insert<SysDict>(model);
        }
        public bool UpdateDicts(SysDict model) {

            opConn().Update<SysDict>(model);
            return true;
        }


     
        public List<DictRes> GetDicts() {
            string sql = @"select id, value ,[label]  ,[d_type],p_id ,type,sort from sys_dict  order by sort";

            return opConn().Query<DictRes>(sql).ToList();
        }









        #endregion

    }
}
